import {
	login
} from "@/common/login.js"
const request = async (path, method = "POST", data) => {
	let token = await uni.getStorageSync('auth')
	//如果该次请求不存在token，且是解析请求，需要重新执行登录方法获得token后,再执行请求
	if (!token && path.indexOf("transNoWaterMark") != -1) {
		await login()
		token = await uni.getStorageSync('auth')
	}
	return new Promise((resolve, reject) => {
		uni.request({
			header: {
				'Authorization': token,
				"content-type": "application/json",
			},
			url: path,
			method: method,
			data: data,
			success: res => {
				//如果请求头中存在token说明token过期了，重新设置token
				if (res.header.token) {
					uni.setStorage({
						key: "auth",
						data: res.header.token
					})
					resolve(res.data)
				}
				//如果请求头中存在expire说明是历史遗留的token不在表中，删除token
				if (res.header.expire == 1) {
					uni.removeStorage({
						key: "auth"
					})
				}
				resolve(res.data)
			},
			fail: error => {
				reject(error)
			}
		})
	})
}

export default request